// pages/listen/listen.js
var that,
  api = new(require('../../utils/api.js')),
  headimg = api.getimgurl(),
  headaudio = api.getaudiourl(),
  app = getApp(),
  util = new(require('../../utils/util.js'));

Page({

  /**
   * 页面的初始数据
   */
  data: {
    onload:!1,
    headimg,
    hasphone:!1,
    swiperList: [],
    navList: [],
    currentageindex: 0,
    checked: !1,
    nav: [],
    pageboxshow:!1,
    start: 1,
    pagesize: 12,
    stateicon: 'show',
    list: [],
    total: "",
    target: {},
    hasphone:!1,
    sendshow:!1,
    imglist:[],
    parenting_price:'',
    classify:[],
    keyword:'',
    cid:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    console.log(options,'optionsoptionsoptionsoptions');

    let isgetphone=wx.getStorageSync('isgetphone'),{parenting_price}=that.data,shareid = 0
    if(options.q){
      shareid  = decodeURIComponent(options.q).replace('https://www.jihemu.com/bookapi/share?id=','');
    }
    if(options.share){
      shareid = options.share
    }
    console.log(shareid,'shareidshareid');

   
    
    if(isgetphone){
      that.setData({isgetphone,hasphone:!0,sendshow:!1})
    }
    that.setData({shareid},()=>{
      if (app.logininfo) {
        that.getdata()
        console.log(0)
      } else {
        util.setwatcher(app, this.afterlogin)
      }
    })
    
   
  },
  afterlogin: {
    token: res => {
      that.getdata();
    }
  },
  getdata() {
    let userinfo = wx.getStorageSync("userinfo")
    if (!userinfo) {
      wx.navigateTo({
        url: '../empower/empower',
      })
    }

    that.setData({onload:!0})
    let { pagesize, cartids,imglist,classify,parenting_price,shareid } = that.data
    if(Number(shareid)>0){
      api.checkshare(shareid,res=>{
        if(res.data.issuccess!=1){
          // wx.showToast({
          //   title: res.data.msg,
          //   icon: 'none'
          // })
        }
        console.log('checkshare');
      })
  }
    // api.getsetting( res => {
    //   if (res.data.issuccess == 1) {
    //     parenting_price=res.data.data.parenting_price;
    //     that.setData({parenting_price})
    //     console.log(parenting_price)
    //   }
    // });
    // api.cate_mp_getlistbyorder(res=>{
    //   if(res.data.issuccess==1){
    //     console.log(res.data,'res.data')
    //     classify=res.data.list
    //   }
    //   that.setData({classify})
    //   console.log(classify,'classifyclassify')
    // })
    // api.getcart(res=>{
    //   if(res.data.issuccess==1){
    //     app.badege(res.data.list);
    //   }
    // })
    api.Coursetypegetlist(res => {
      if (res.data.issuccess == 1) {
        let nav=res.data.list
        that.setData({ nav,cid:nav[0].id},()=>{
          that.getlist()
        })
      }
    })
    // that.getnav(() => {
    //   that.getlist()
    // })
    // api.getallswiper({type:'LISTEN'},res=>{
    //   if(res.data.issuccess==1){
    //     console.log(res.data,'getallswipergetallswipergetallswiper')
    //     imglist=res.data.list
    //     that.setData({imglist})
    //   }
    // })
    // api.getmain(pagesize, res => {
    //   if (res.data.issuccess == 1) {
    //     let //swiper = JSON.parse(util.decodeurl(res.data.data.swiper)),
    //       awards = res.data.data.awards,
    //       masters = res.data.data.masters,
    //       //list = res.data.data.recommend,
    //       cart = res.data.data.cart,
    //       setting = res.data.data.settings;
    //     // app.badege(cart);
    //     wx.setStorageSync("setting", setting);
    //     let target = {
    //         //swiper,
    //         awards,
    //         masters
    //       }
    
    //     // that.setData({ cartids})
    //     // swiper.imgs.forEach((x, i) => {
    //     //   if (x.indexOf(headimg) == -1) {
    //     //     swiper.imgs[i] = headimg + x;
    //     //   }
    //     // });
    //     awards.forEach((x, i) => {
    //       if (x.thumbpath.indexOf(headimg) == -1) {
    //         awards[i].thumbpath = headimg + x.thumbpath;
    //       }
    //     })
     
    //     that.setData(target)
    //   }
    // });
  },
  toshare(){
    // wx.navigateTo({
    //   url: '../sampleReels/sampleReels',
    // })
    wx.switchTab({
      url: '../share/share',
    })
  },
  // toswiperdetail(e){
  //   console.log(e,'imglistiiiii')
  //   let {id}=e.currentTarget.dataset
  //   wx.navigateTo({
  //     url: '../swiperdetail/swiperdetail?id='+id,
  //   })
  // },

  inputchange(e){
    console.log(e,'eeeeeee')
    if(e.detail.value==''){
      that.setData({list:[]})
      that.getlist()
    }
  },
  getPhoneNumber(e){
    let {hasphone,sendshow}=that.data
    api.getphone({edata:e.detail.encryptedData,iv:e.detail.iv},res=>{
      if(res.data.issuccess==1){
        let data = JSON.parse(res.data.data);
        let isgetphone=true
        wx.setStorageSync('isgetphone', isgetphone)
        that.setData({hasphone:!0,sendshow:!1,isgetphone})
        console.log(data.phoneNumber.phoneNumber,'data')
        let phone=data.phoneNumber
        console.log(phone,'phonephonephone');
        //更新用户手机号
        api.getuserphone(phone,res=>{
          if(res.data.issuccess==1){
            console.log(res.data,'phone')
          }
        })
      }
    })
  },

  todetail(e) {
    let {id} = e.currentTarget.dataset ,{isgetphone}=that.data;
    console.log(id,'ididid');
      if(!isgetphone){
        that.setData({sendshow:!0})
      }else{
        wx.showLoading({
          title: '加载中',
        })
        wx.navigateTo({
          url: '../subject/subject?cid='+ id 
        })
      }
  },
  no(){
    that.setData({sendshow:!1})
  },
  formsubmit(e) {
    api.gatherformid(e, res => {
    })
  },
  cancel(){
    that.setData({payshow:!1})
  },

  getnav() {
    let nav = [];
    api.Coursetypegetlist(res => {
      if (res.data.issuccess == 1) {
        nav=res.data.list
        that.setData({ nav})
      }
    })
  },
  getlist() {
    let {start, pagesize, list,keyword,cid} = that.data;
    api.Testquestionsgetlist({ start, pagesize, cid,keyword }, res => {
      if (res.data.issuccess == 1) {
        that.formatlist((res.data.list), () => {
          console.log(list, 'list')
          that.setData({
            reachbtm: list.length == res.data.total,
             total: res.data.total
          },()=>{
            that.getpage()
          })
        })
      }

    })
  },

  

  getpage(){
    let { total, pagesize } = that.data, pagenumber, pageitem = [], left, right,item
    pagenumber = Math.ceil(total / pagesize)
    for (let i = 0; i < pagenumber;i++){
      if (i != pagenumber-1){
        left = i * pagesize + 1
        right = i * pagesize + pagesize
        item=left+'~'+right
        pageitem.push({ item })
      }else{
        left = i * pagesize + 1
        right = total
        if(left==right){
          item = left
        }else{
          item = left + '~' + right
        }
        pageitem.push({ item })
      }
    }
    that.setData({ pageitem })
  },
  itemstart(e){
    let { pagesize } = that.data,{ pageindex } = e.currentTarget.dataset
    that.setData({
      start: pageindex * pagesize, pageboxshow: !1, stateicon: 'show',list:[]
    }, () => {
      wx.pageScrollTo({
        selector: '.list',
        scrollTop: 0,
        duration: 0,
      })
      that.getlist()
    })
  },
  formatlist(getlist, reachbtm) {
    let {
      list
    } = that.data
    let newlist = getlist.map((x, i) => {
      x['imgsrc'] = headimg + x.imgsrc,
      x['date']= util.toDate(x.updateDate);
      x['title']= x.title.replace(/&#39;/g,'\'');
      // x.views = x.views >= 10000 ? (x.views / 10000).toFixed(1) + "万" : x.views
      return x;
    })
    let targetlist = list.concat(newlist);
    that.setData({
      list: targetlist
    }, () => {
      reachbtm()
    })

  },


  chose(e) {
    wx.pageScrollTo({
      selector: '.list',
      scrollTop: 0,
      duration: 0,
    })

    let {
      currentageindex
    } = e.currentTarget.dataset, {
      nav
    } = this.data, cateindex = that.data.currentageindex;
    if (cateindex == currentageindex) return;
    /*获取可视窗口宽度*/
    　
    let w = wx.getSystemInfoSync().windowWidth,
      leng = nav.length,
      disX = (currentageindex - 1) * w / leng;
    this.setData({
      list: [],
      'navleft': disX,
      start: 1,
      cid: nav[currentageindex].id,
      currentageindex, pageboxshow: !1, stateicon: 'show',
      toview: 'item' + currentageindex,keyword:''
    }, () => {
      that.getlist()
    });
  },


  isshow() {
    console.log(1111)
    if (that.data.pageboxshow == !1) {
      console.log(22222)
      that.setData({
        stateicon: 'hide',
        pageboxshow: !0
      })
    } else {
      console.log(333333)
      that.setData({
        stateicon: 'show',
        pageboxshow: !1
      })
    }
  },

  // 搜索
  tosearch(e) {
    let keyword = e.detail.value
    that.setData({keyword,list: [],start: 1,},()=>{
      that.getlist()
    })

  },
  // goToBangDan:function(e){
  //   let {id,index} =e.currentTarget.dataset
  //   console.log(e,'goToBangDangoToBangDan')
  //   wx.navigateTo({
  //     url: '/pages/guideread/guideread?id='+id +'&navindex=' + index,
  //   })
  // },

  // gotoHelp(){
  //   wx.navigateTo({
  //     url: '/pages/helps/helps',
  //   })
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // let {onload}=that.data
    // if(onload){
    //   console.log(app,'appappappapp');
      
    // let appletname=app.logininfo.appletname
    //   wx.setNavigationBarTitle({
    //     title: appletname  || '小巴学堂',
    //   })
      
    // }
    let isgetphone=wx.getStorageSync('isgetphone')
    
  
    if(isgetphone){
      that.setData({isgetphone,hasphone:!0,sendshow:!1})
    }
    wx.hideLoading();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    that.setData({
      start: 1,list:[]
    }, () => {
      that.getlist()
    })
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let {
      start, total
    } = this.data;
    if (start>total) {
      that.setData({ reachbtm:true})
      // wx.showToast({
      //   icon: "none",
      //   title: '再怎么扯也没有了',
      // })
      return
    }
    that.setData({
      start: that.data.start + that.data.pagesize
    }, () => {
      that.getlist()
    })
  },

  onShareTimeline(){
    return {
      title: '123',
      query: `abc=1`,
      imageUrl: `../pic/account-fill.png`,
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: that.data.appletname,
      path: `pages/listen/listen?share=`+app.logininfo.userid,
    }
  }
})